import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { CreateScenicSpotDto } from './dto/create-scenic-spot.dto';
import { ScenicSpotEntity } from './entities/scenic-spot.entity';
import { CityEntity } from 'src/city/entities/city.entity';


import { UpdateScenicSpotDto } from './dto/update-scenic-spot.dto';

@Injectable()
export class ScenicSpotService {
  constructor(
    @InjectRepository(ScenicSpotEntity)
    private repo: Repository<ScenicSpotEntity>,
    @InjectRepository(CityEntity)
    private cityRepo: Repository<CityEntity>,
  ) {}

  async findAll(): Promise<ScenicSpotEntity[]> {
    return this.repo.find({ relations: ['city'] });
  }

  async findOne(id: number): Promise<ScenicSpotEntity> {
    const spot = await this.repo.findOne({ where: { id }, relations: ['city'] });
    if (!spot) throw new NotFoundException('景区不存在');
    return spot;
  }

  async update(id: number, dto: UpdateScenicSpotDto): Promise<ScenicSpotEntity> {
    const spot = await this.repo.findOne({ where: { id } });
    if (!spot) throw new NotFoundException('景区不存在');
    Object.assign(spot, dto);
    return this.repo.save(spot);
  }

  async remove(id: number) {
    const res = await this.repo.delete(id);
    if (res.affected === 0) throw new NotFoundException('景区不存在或已删除');
    return { message: '删除成功' };
  }

  async findByCity(cityId: number): Promise<ScenicSpotEntity[]> {
    return this.repo.find({
      where: { city: { id: cityId } },
      relations: ['city'],
    });
  }

  async create(dto: CreateScenicSpotDto): Promise<ScenicSpotEntity> {
    const city = await this.cityRepo.findOne({ where: { id: dto.cityId } });
    if (!city) throw new NotFoundException('城市不存在');
    const spot = this.repo.create({
      name: dto.name,
      address: dto.address,
      photoUrl: dto.photoUrl,
      city,
    });
  
    return this.repo.save(spot);
  }
}
